/**
 *
 * @author Doan Tuan Anh
 */
import java.util.Random;

public class ClownFishThread extends Thread {

    private boolean pause, stop;
    private ClownFish[] clownFishes;
    private Random random = new Random();
    private int[] fish_pos;

    ClownFishThread(MyGameCanvas canvas) throws Exception {
        clownFishes = canvas.getClownFishes();
        fish_pos = canvas.getLayerManager().fish_pos;
    }
  
    synchronized void pauseGame() {
        pause = true;
    }

    synchronized void resumeGame() {
        pause = false;
        notify();
    }

    synchronized void requestStop() {
        stop = true;
        notify();
    }

    public void run() {
        stop = false;
        pause = false;

        while (true) 
        {
            if (stop) break;
            
            synchronized(this)
            {
                while (pause) 
                {
                    try 
                    {
                        wait();
                    } 
                    catch (Exception e) {}
                }
            }
            int waitTime = (1 + random.nextInt(10)) * 100;
            
            synchronized(this) {
                try {
                    wait(waitTime);
                } 
                catch(Exception e) {}
            }
            
            if (!pause) 
            {
                 int whichFish = random.nextInt(clownFishes.length);
                 int whichLocation = random.nextInt(fish_pos.length);
            
                 clownFishes[whichFish].go(random.nextInt(2) == 0, fish_pos[whichLocation]);
            }
        }
    }
}
